﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;

public class FollowActionPriorityQueue
{
    #region Singleton

    private static FollowActionPriorityQueue instance = null;

    public static FollowActionPriorityQueue Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new FollowActionPriorityQueue();
            }
            return instance;
        }
    }

    private FollowActionPriorityQueue()
    {

    }

    #endregion

    private List<PrioritizedFollowPosition> queue = new List<PrioritizedFollowPosition>();

    private PrioritizedFollowPosition lastReturned = null;

    public void AddFollowPosition(PrioritizedFollowPosition followPosition)
    {
        UnityEngine.MonoBehaviour.print("Follow position of type " + followPosition.GetType().ToString() + " added");
        queue.Add(followPosition);
    }


    public Vector3 GetHighestFollowPosition(float timeDelta)
    {
        List<PrioritizedFollowPosition> expired = new List<PrioritizedFollowPosition>();
        foreach (PrioritizedFollowPosition followPosition in queue)
        {
            followPosition.Update(timeDelta);
            if (followPosition.Priority == 0)
                expired.Add(followPosition);
        }

        foreach (PrioritizedFollowPosition expiredTarget in expired)
        {
            UnityEngine.MonoBehaviour.print("Culling expired follow target of type " + expiredTarget.GetType().ToString());
            queue.Remove(expiredTarget);
        }

        int highestPriority = queue.Max(p => p.Priority);
        PrioritizedFollowPosition target = queue.First(p => p.Priority == highestPriority);
        if (target != lastReturned)
        {
            UnityEngine.MonoBehaviour.print("Changing targets to " + target.GetType().ToString() + " with priority " + target.Priority);
        }
        lastReturned = target;
        return target.Position;
    }


}
